package org.zn.mvcbase.service;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.zn.commons.reflection.ObjectInvoker;
import org.zn.mvcbase.mybatis.CommonsMapper;
import org.zn.mvcbase.mybatis.CreateTimeExamples;
import org.zn.mvcbase.mybatis.ExampleProvider;
import org.zn.mvcbase.page.PaginationUtility;
import org.zn.mvcbase.page.Pagnation;

import tk.mybatis.mapper.entity.Example;


public abstract class CommonCrudService<E,M extends CommonsMapper<E>> {
	
	protected Logger logger  =  LoggerFactory.getLogger(CommonCrudService.class);
	
//	protected Class<?> entityClass;
//	protected Class<?> mapperClass;
//	
	@Autowired
	protected M commonsMapper;

	@Autowired
	protected CreateTimeExamples  createTimeExamples;
	
	
//	public  CommonCrudService() throws ClassNotFoundException  {  
//      
//        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();  
//                
//        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();  
//        
//        entityClass=Class.forName(actualTypeArguments[0].getTypeName());
//        mapperClass=Class.forName(actualTypeArguments[1].getTypeName());
//        
//        logger.info(parameterizedType +" init ");
//        
//    }  

	
	
	@Pagnation
	public List<E> querylist(PaginationUtility<?> pu,E entity,String time1,String time2){
		
		
		Example ex=ExampleProvider.wrapperEntity(entity).provider();
		
		if(Objects.nonNull(entity)) createTimeExamples.doAndCondition(ex, time1, time2);	
		
		return commonsMapper.selectByExample(ex);
		
	}
	
	
	
	public E queryById(String id) {
		
		return commonsMapper.selectByPrimaryKey(id);
		
	}
	

	public void saveUpdate(E bm) {
		
		String id=null;
	 	try {
	 		id=(String) ObjectInvoker.wrapper(bm).InvokeMethod("getId");
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		if(Objects.isNull(id) ) {
			
			commonsMapper.insertSelective(bm);
		
		}else {
			
			commonsMapper.updateByPrimaryKeySelective(bm);
			
		}
		
	}
	
	public void delById(String id) {
		
		commonsMapper.deleteByPrimaryKey(id);
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
